package com.woniu.controller;


import com.woniu.commons.Result;
import com.woniu.commons.SaltUtil;
import com.woniu.controller.component.ControllerBase;
import com.woniu.controller.form.DeleteStaff;
import com.woniu.controller.form.LoginForm;
import com.woniu.model.BmsDept;
import com.woniu.model.BmsPermission;
import com.woniu.model.BmsRole;
import com.woniu.model.BmsUser;
import com.woniu.service.IBmsUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Kevin Kwok
 * @since 2021-04-13
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class BmsUserController extends ControllerBase {

    @Resource
    private IBmsUserService userService;

    @GetMapping("/test")
    public String test(){
        return "success";
    }

    @RequestMapping("/login")
    public Result login(@Valid LoginForm loginForm,HttpSession session, BindingResult bindingResult){
        log.info("登录参数：{}", loginForm);
        Result result = extractError(bindingResult);
        if (result != null) {
            log.info("参数错误：{}", result);
            return result;
        }
        //将登录操作交给shiro
        UsernamePasswordToken token = new UsernamePasswordToken(loginForm.getTel(), loginForm.getPassword(),loginForm.getRememberMe());
        Subject subject = SecurityUtils.getSubject();

        if(! subject.isAuthenticated() && ! subject.isRemembered() ){
            subject.login(token);
        }
        //往session中存值
        BmsUser bmsUser = userService.queryUserByTel(loginForm.getTel());
        session.setAttribute("logined",bmsUser);
        //shiro的认证没有直接返回错误就表示没问题，直接返回成功的状态
        return new Result("200", "success", bmsUser, null);
    }

    @GetMapping("/menu")
    public Result getMenu(HttpSession session) throws Exception {
        BmsUser logined = (BmsUser)session.getAttribute("logined");
        System.out.println("登录后的账户:"+logined);
        List<BmsPermission> bmsPermissions = userService.queryUserPermission(logined);
        System.out.println(bmsPermissions);
        return new Result("200", "success", bmsPermissions, null);
    }

    @GetMapping("/unlogin")
    public Result unlogin(){
        return new Result("400","unlogin",null,null);
    }

    @GetMapping("/logout")
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new Result("200","注销成功",null,null);
    }

    @GetMapping("/allUsers")
    public Result queryAllUser(){
        List<BmsUser> bmsUsers = userService.queryAllUser();
        return new Result("200","success",null,bmsUsers);
    }

    @GetMapping("/allDept")
    public Result queryAllDept(){
        List<BmsDept> bmsDepts = userService.queryAllDept();
        return new Result("200","success",null,bmsDepts);
    }

    @GetMapping("/allRole")
    public Result queryAllRole(){
        List<BmsRole> bmsRoles = userService.queryAllRole();
        return new Result("200","success",null,bmsRoles);
    }
    @RequiresPermissions({"新增员工"})
    @GetMapping ("/addUser")
    public Result addNewUser(BmsUser bmsUser){
        log.info("新增用户参数：{}", bmsUser);
        //设置盐
        bmsUser.setSault(SaltUtil.getSalt(8));
        //执行加密
        String s = new Md5Hash(bmsUser.getPassword(), bmsUser.getSault(), 1024).toHex();
        bmsUser.setPassword(s);
        int i = userService.addNewUser(bmsUser);
        if(i==0){
            return new Result("400","新增失败",null,null);
        }
        return new Result("200","新增成功",bmsUser,null);
    }

    @RequiresPermissions({"删除员工"})
    @GetMapping("/deleteStaff")
    public Result deleteStaff(DeleteStaff staff){
        int i = userService.deleteStaff(staff);
        if(i==0){
            return new Result("400","删除失败",null,null);
        }
        return new Result("200","删除成功",null,null);
    }
}

